/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *  SRVMotorControllerOperation.m - iPhoneSRV console for Surveyor SRV-1 and SVS 
 *
 *  Created by Nick Kitchener.  Copyright (C) 2009  Surveyor Corporation 
 *            and Nick Kitchener.  All rights reserved.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details (www.gnu.org/licenses)
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

/* direct motor control
 * TX: 'Mabc' abc parameters sent as 8-bit binary
 * RX: '#M'
 * 
 *  Where
 *   a=left speed
 *   b=right speed
 *   c=duration*10milliseconds 
 *
 *   speeds are 2's complement 8-bit binary values
 *   0x00 through 0x7F is forward,
 *   0xFF through 0x81 is reverse,
 *   e.g. the decimal equivalent of the 4-byte sequence 0x4D 0x32 0xCE 0x14 = 'M' 50 -50 20 (rotate right for 200ms) 
 * duration of 00 is infinite, e.g. the 4-byte sequence 0x4D 0x32 0x32 0x00 = M 50 50 00 (drive forward at 50% indefinitely)
 */

#import "SRVMotorControllerOperation.h"

@implementation SRVMotorControllerOperation

-(id)initWithValues:(int)left right:(int)right duration:(int)duration {
	if( self = [super init] ) {
		request = [[SRVStreamingRequestBuffer alloc] init];
		response = [[SRVStreamingSelfTerminatedStringResponseBuffer alloc] init];
		NSString *reqString = [NSString stringWithFormat:@"M%02x%02x%02x", left, right, duration];
		[request setRequestString:reqString];
	}
	return self;
}

-(void) dealloc {
	[request release];
	request=nil;
	[response release];
	response=nil;
	[super dealloc];
}

-(void)haveBytes:(CFReadStreamRef)inputStream {
	[response haveBytes:inputStream];
	if([response isComplete]) {
		complete = YES;
	}
}

-(void)haveSpace:(CFWriteStreamRef)outputStream {
	[request haveSpace:outputStream];
}

+(SRVMotorControllerOperation*)setMotorSpeedLeft:(int)left right:(int)right duration:(int)duration {
	return [[SRVMotorControllerOperation alloc]initWithValues:left right:right duration:duration];
}

@end
